<script setup>
// 用户搜索的字段数据
import {reactive, ref} from "vue";
import moment from "moment";
import {
  DeactiveUser, DeprtUser,
  GetDepartUser,
  GetSearchUser,
  GetTeachersData,
  GetTypeUser,
  ResettingUserPassword
} from "@/api/index.js";
import AddTeacher from "@/components/usermanagement_teainfo/AddTeacher.vue";
import UpdateTeacher from "@/components/usermanagement_teainfo/UpdateTeacher.vue";
import {ElMessage, ElMessageBox} from "element-plus";
const tableData = ref([]);
// 分页
const total = ref();
// 赋值数据
let pageSize = ref(5);
let currentPage = ref(1);
const Search_Data = reactive({
  username: null,
  mobile: null,
  email:null,
  type:1
});

//对话框
const title = ref();
const dialogTableVisible = ref(false);
const handleCloseDialog = ()=>{
  dialogTableVisible.value = false
}

// 修改老师信息
const dialogTableVisible2 = ref(false)
const update_data = ref()

const handleRemoveSearchData = ()=>{
  for(let i in Search_Data){
    Search_Data[i] = null
  }
  Search_Data.type = 1
}
const handleSearchTeaInfo = async(data)=>{
  try {
    const res  = await GetSearchUser({...Search_Data,...data})
    tableData.value = res.results
    total.value = res.count
    handleRemoveSearchData()
  } catch (error) {
    console.log(error);
  }
}
const handleSearchTeaInfoBtn = async ()=>{
  currentPage.value = 1
  await handleSearchTeaInfo({
    page: currentPage.value,
    size: pageSize.value,
  })
}
//分页器
const handleCurrentChange = async (val) => {
  currentPage.value = val;
  f({
    page:val,
    size:pageSize.value,
  })
};
// 获取所有老师的数据
const handleGetTeachersData =async (data)=>{
  try {
    const res = await GetTeachersData(data)
    tableData.value = res.results
    total.value =res.count
  } catch (error) {
    console.log(error)
  }
}
handleGetTeachersData({
  page:currentPage.value,
  size:pageSize.value,
})
// 通过职位查询对应类型的老师
const typeUser = ref(null)
// 职位选项
const POSITION_TYPE = [
  {
    id: 0,
    label: '校长',
  },
  {
    id: 1,
    label: '教导主任',
  },
  {
    id: 2,
    label: '普通老师',
  },
  {
    id: 3,
    label: '班主任',
  },
]
const handleReqTypePosition = async(data)=>{
  try {
    const res = await GetTypeUser({type:typeUser.value,...data})
    tableData.value = res.results
    total.value = res.count
    typeUser.value = null
  } catch (error) {

  }
}
const handleTypePosition = ()=>{
  currentPage.value = 1
  handleReqTypePosition({
    page:currentPage.value,
    size:pageSize.value,
  })
}

// 打开添加老师信息的弹窗
const handleOpenAddTeacherPopup = () => {
  dialogTableVisible.value = true
}
// 添加老师信息
const handleAddTeacher = (data)=>{
  tableData.value.push(data)
}

// 打开更新老师信息的弹窗
const handleOpenUpdateTeacherPopup = (val) => {
  update_data.value = val
  dialogTableVisible2.value = true
}

// 获取离职老师的信息
const handleGetDepartUser = async(data)=>{
  try {
    const res = await GetDepartUser(data)
    tableData.value = res.results
    total.value = res.count
  } catch (error) {
    console.log(error);
  }
}
const handleGetDepartUserBtn = ()=>{
  currentPage.value = 1
  handleGetDepartUser({
    page:currentPage.value,
    size:pageSize.value,
  })
}
// 移除老师信息
const handleDeleteTeacher = (id)=>{
  ElMessageBox.confirm(
      '确定移除此老师信息吗?',
      '移除老师',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }
  )
      .then(async() => {
        try {
          await DeprtUser({id})
          tableData.value = tableData.value.filter(item=>item.id!==id)
          total.value--
          ElMessage.success("操作成功")
        } catch (error) {
          ElMessage.error('网络错误，请稍后尝试移除！')
        }
      })

}

// 封号
const handleEdit = async (id, number)=>{
  try {
    const res = await DeactiveUser({id})
    if (res.status===201){
      const index = tableData.value.findIndex(item=>item.id===id)
      tableData.value[index].is_active  = !tableData.value[index].is_active
      ElMessage.success(res.msg)
    }else{
      ElMessage.error(res.msg)
    }
  } catch (error) {
    console.log(error);
  }
}

//重置用户密码
const handleResettingPassword = async(id)=>{
  ElMessageBox.confirm(
      '确定重置此老师登录密码吗?',
      '重置登录密码',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }
  )
      .then(async() => {
        try {
          const res = await ResettingUserPassword({id})
          res.status===201?ElMessage.success(res.msg):ElMessage.error(res.msg)
        } catch (error) {
          ElMessage.error('网络错误，请稍后尝试重置！')
        }
      })

}

const handleRemoveUpdateTeacherPopup = (id,position)=>{
  if (id){
    const  index = tableData.value.findIndex(item=>item.id===id)
    const position_type =  POSITION_TYPE.filter(item=>item.id===position)
    tableData.value[index].userdetail.position = position_type[0].label
  }
  dialogTableVisible2.value = false
}

</script>

<template>
  <div class="search">
    <div class="mt-4">
      账号：
      <el-input style="width: 800px" v-model="Search_Data.username" placeholder="请输入账号进行查询"
                class="input-with-select">
      </el-input>
    </div>
    <div class="mt-4">
      手机：
      <el-input style="width: 800px" v-model="Search_Data.mobile" placeholder="请输入手机号进行查询"
                class="input-with-select">
      </el-input>
    </div>
    <div class="mt-4">
      邮箱：
      <el-input style="width: 800px" v-model="Search_Data.email" placeholder="请输入邮箱进行查询"
                class="input-with-select">
      </el-input>
    </div>


    <div class="button">
      <el-button type="primary" @click="handleSearchTeaInfoBtn">查询</el-button>
    </div>
  </div>

  <div class="list">
    <div class="query">
      <div style="margin-right: 20px;width: 200px" >
        <el-select v-model="typeUser" class="m-2" placeholder="请选择职位进行查询" size='default'>
          <el-option v-for="item in POSITION_TYPE" :key="item.id" :label="item.label" :value="item.id"
                     @click="handleTypePosition"/>
        </el-select>
      </div>
      <el-button type="success" @click="handleGetTeachersData">查询所有</el-button>
      <el-button type="info" @click="handleOpenAddTeacherPopup">添加老师</el-button>
      <el-button type="danger" @click="handleGetDepartUserBtn">查询离职人员</el-button>
    </div>
    <el-table v-if="tableData" :data="tableData" style="width: 1600px">

      <el-table-column label="入职时间" width="250" header-align="center">
        <template #default="scope">
          <div style="display: flex; align-items: center; margin-left: 20px">
            <span style="margin-left: 10px"> {{ moment(scope.row.date_joined).format('YYYY-MM-DD HH:mm:ss') }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="账号" width="120" header-align="center">
        <template #default="scope">
          <span style="margin-left: 10%">{{ scope.row.username }}</span>
        </template>
      </el-table-column>

      <el-table-column label="名称" width="120" header-align="center">
        <template #default="scope">
          <span style="margin-left: 10%">{{ scope.row.first_name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="职位" width="150" header-align="center">
        <template #default="scope">
          <div>
            <span style="margin-left: 20%"> {{
                scope.row.userdetail && scope.row.userdetail.position ?
                    scope.row.userdetail.position : ''
              }}</span>

          </div>
        </template>
      </el-table-column>
      <el-table-column label="年龄" width="60" header-align="center">
        <template #default="scope">
          <span style="margin-left: 20%">
            {{ scope.row.userdetail && scope.row.userdetail.age ? scope.row.userdetail.age : '' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="性别" width="60" header-align="center">
        <template #default="scope">
          <span>
            {{ scope.row.userdetail && scope.row.userdetail.sex ? scope.row.userdetail.sex : '' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="联系方式" width="120" header-align="center">
        <template #default="scope">
          {{ scope.row.userdetail && scope.row.userdetail.mobile ? scope.row.userdetail.mobile : '' }}
        </template>
      </el-table-column>
      <el-table-column label="邮箱" width="190" header-align="center">
        <template #default="scope">
          <span style="margin-left: 16%">{{ scope.row.email }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系地址" width="200" header-align="center">
        <template #default="scope">
          {{ scope.row.userdetail && scope.row.userdetail.address ? scope.row.userdetail.address : '' }}
        </template>
      </el-table-column>

      <el-table-column label="操作" header-align="center" width="300">
        <template #default="scope">
          <div>
            <el-button size="small" @click="handleOpenUpdateTeacherPopup(scope.row)">修改</el-button>
            <el-button type="danger" size="small" @click="handleDeleteTeacher(scope.row.id)">离职</el-button>
            <el-button size="small" type="success" @click="handleEdit(scope.row.id, 0)"
                       v-if="scope.row.is_active">封号
            </el-button>
            <el-button size="small" type="info" @click="handleEdit(scope.row.id,0)" v-else>解封</el-button>
            <el-button type="warning" size="small" @click="handleResettingPassword(scope.row.id)">重置</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <div class="pagination" v-if="total > 0">
    <el-pagination @current-change="handleCurrentChange" :page-size="pageSize" layout="prev, pager, next" :total="total"
                   class="mt-4" :current-page="currentPage"/>
  </div>

  <el-dialog v-model="dialogTableVisible" :title="title" center width="700">
    <AddTeacher :handleAddTeacher="handleAddTeacher" :handleCloseDialog="handleCloseDialog"/>
  </el-dialog>

  <el-dialog v-model="dialogTableVisible2" :title="title" center width="700">
    <UpdateTeacher :update_data="update_data" :handleRemoveUpdateTeacherPopup="handleRemoveUpdateTeacherPopup"/>
  </el-dialog>
</template>

<style scoped lang="less">
.search {
  width: 900px;
  margin: auto;
  background: #fff;
  border: 1px solid #e2e2e2;
  box-shadow: 0 8px 30px rgb(0 80 179 / 12%);
  border-radius: 10px;

  .mt-4 {
    margin-bottom: 20px;
    margin-left: 20px;

    .el-input {
      width: 300px;
    }
  }

  .button {
    width: 400px;
    margin: auto;
    padding-bottom: 20px;

    .el-button {
      width: 400px;
    }
  }

  .mt-4:nth-child(1) {
    margin-top: 20px;
  }
}

.list {
  width: 100%;

  .el-table {
    margin: auto;
  }
  .query {
    display: flex;
    justify-content: flex-end;
    padding: 10px 90px;
    .el-button {
      width: 100px;
    }
  }
}

.pagination {
  width: 100%;

  .el-pagination {
    width: 200px;
    margin: 20px auto;
  }
}
</style>